package com.threeti.jiayusms.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.threeti.jiayusms.domain.model.CommunicationMessage;
import com.threeti.jiayusms.domain.model.CommunicationRule;
import com.threeti.jiayusms.domain.model.CommunicationTime;
import com.threeti.jiayusms.domain.model.CommunicationVoice;
import com.threeti.jiayusms.domain.model.defaulttemplate.DefaultCommunicationTemplate;
import com.threeti.jiayusms.domain.model.defaulttemplate.SMSTemplateMapping;
import com.threeti.jiayusms.domain.model.defaulttemplate.VoiceTemplateMapping;
import com.threeti.jiayusms.domain.model.legacy.Condition;
import com.threeti.jiayusms.domain.model.legacy.ConditionType;
import com.threeti.jiayusms.domain.model.legacy.Node;
import com.threeti.jiayusms.domain.model.legacy.PreviewOrder;
import com.threeti.jiayusms.domain.model.legacy.ProductType;
import com.threeti.jiayusms.domain.service.communicationmessage.CommunicationMessageQueryService;
import com.threeti.jiayusms.domain.service.communicationrule.CommunicationRuleQueryService;
import com.threeti.jiayusms.domain.service.communicationtime.CommunicationTimeQueryService;
import com.threeti.jiayusms.domain.service.communicationvoice.CommunicationVoiceQueryService;
import com.threeti.jiayusms.domain.service.defaulttemplate.DefaultCommunicationTemplateQueryService;
import com.threeti.jiayusms.domain.service.defaulttemplate.DefaultCommunicationTemplateUpdateService;
import com.threeti.jiayusms.domain.service.legacy.JiaYuDBLegacyQueryService;
import com.threeti.jiayusms.domain.util.TemplateIdGenerator;
import com.threeti.jiayusms.framework.util.DynaSearchCriteria;
import com.threeti.jiayusms.framework.util.PagedListHandler;
import com.threeti.jiayusms.framework.web.PagedQueryControllerAdapter;
import com.threeti.jiayusms.interfaces.facade.JiaYuSystemQueryFacade;
import com.threeti.jiayusms.web.form.DefaultTemplateForm;
import com.threeti.jiayusms.web.form.MessageTemplateForm;

@Controller
@SessionAttributes("DefaultTemplateForm.DefaultTemplateDynaCriteria")
public class DefaultTemplateMainController {

  @Autowired
  private DefaultCommunicationTemplateQueryService queryService;

  @Autowired
  private CommunicationMessageQueryService msgQueryService;

  @Autowired
  private CommunicationVoiceQueryService voiceQueryService;

  @Autowired
  private CommunicationRuleQueryService ruleQueryService;

  @Autowired
  private CommunicationTimeQueryService timeQueryService;
  
  @Autowired
  private JiaYuSystemQueryFacade queryFacade;
  
  @Autowired
  private JiaYuDBLegacyQueryService legacyQueryService;

  @Autowired
  private DefaultCommunicationTemplateUpdateService updateService;

  @RequestMapping(value="/defaultTemplateMain.html")
  public String enterDefaultTemplateMain(HttpServletRequest request, Map modelMap) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<DefaultCommunicationTemplate> pagedDefaultTemplates = queryService.findAllDefaultTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedDefaultTemplates, request);

    modelMap.put("defaultTemplates", pagedDefaultTemplates.getPageList());

    return "plan/defaultTemplateMain";
  }

  @RequestMapping(value="/searchDefaultTemplateByPage.html")
  public String searchDefaultTemplate(HttpServletRequest request, @ModelAttribute DefaultTemplateForm form, Map modelMap) {

    DynaSearchCriteria dynaSearchCriteria = null;

    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    if (pagedHelper.isAnyPageSearch(request)) {
      dynaSearchCriteria = (DynaSearchCriteria)modelMap.get(DefaultTemplateForm.SESSION_DYNA_CRITERIA_KEY);
    } else {
      modelMap.put(MessageTemplateForm.SESSION_DYNA_CRITERIA_KEY, (dynaSearchCriteria = form.buildDynaSearchCriteriaBy("com.threeti.jiayusms.interfaces.DefaultTemplateDynaCriteriaDto")));
    }
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<DefaultCommunicationTemplate> pagedDefaultTemplates = queryService.findDefaultTemplatesByPage(dynaSearchCriteria, index[0], index[1]);
    pagedHelper.processPage(pagedDefaultTemplates, request);

    modelMap.put("defaultTemplates", pagedDefaultTemplates.getPageList());

    return "plan/defaultTemplateMain";
  }

  @RequestMapping(value="/newDefaultTemplateForm.html")
  public String newDefaultTemplateForm(@ModelAttribute DefaultTemplateForm form, Map modelMap) {
    //渲染节点下拉框
    List<Node> nodes = legacyQueryService.findAllNodes();
    Map<String, String> nodeMap = new LinkedHashMap();
    for (Node node : nodes) {
      nodeMap.put(node.getNcode(), node.getNname());
    }
    form.setNodeMap(nodeMap);
    
    //渲染产品类型下拉框
    List<ProductType> pTypes = legacyQueryService.findAllProductTypes();
    Map<String, String> productTypeMap = new LinkedHashMap();
    for (ProductType pType : pTypes) {
      productTypeMap.put(pType.getPcode(), pType.getPname());
    }
    form.setProductTypeMap(productTypeMap);
    
    //渲染条件类型下拉框
    List<ConditionType> cTypes = legacyQueryService.findAllConditionTypes();
    Map<String, String> conditionTypeMap = new LinkedHashMap();
    for (ConditionType cType : cTypes) {
      conditionTypeMap.put(cType.getCcode(), cType.getCname());
    }
    form.setConditionTypeMap(conditionTypeMap);
    
    //渲染条件值下拉框
    List<Condition> conditions = legacyQueryService.findAllConditions();
    Map<String, String> conditionMap = new LinkedHashMap();
    for (Condition c : conditions) {
      conditionMap.put(c.getCvcode(), c.getCvname());
    }
    form.setConditionMap(conditionMap);
    
    //短信方式列表
    //语音方式列表
    
    return "plan/newDefaultTemplateForm";
  }
  
  //快速选取功能区->
  @RequestMapping(value="/quickViewMsgTemplate.html")
  public String quickViewMsgTemplate(Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationMessage> pagedMsgTemplates = msgQueryService.findAllMsgTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedMsgTemplates, request);
    
    modelMap.put("msgTemplates", pagedMsgTemplates.getPageList());

    return "plan/quickViewMsgTemplate";
  }

  @RequestMapping(value="/quickViewVoiceTemplate.html")
  public String quickViewVoiceTemplate(Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationVoice> pagedVoiceTemplates = voiceQueryService.findAllVoiceTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedVoiceTemplates, request);
    
    modelMap.put("voiceTemplates", pagedVoiceTemplates.getPageList());

    return "plan/quickViewVoiceTemplate";
  }

  @RequestMapping(value="/quickViewMsgRuleTemplate.html")
  public String quickViewMsgRuleTemplate(Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationRule> pagedVoiceTemplates = ruleQueryService.findAllRuleTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedVoiceTemplates, request);
    
    modelMap.put("ruleTemplates", pagedVoiceTemplates.getPageList());

    return "plan/quickViewMsgRuleTemplate";
  }

  @RequestMapping(value="/quickViewVoiceRuleTemplate.html")
  public String quickViewVoiceRuleTemplate(Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationRule> pagedVoiceTemplates = ruleQueryService.findAllRuleTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedVoiceTemplates, request);
    
    modelMap.put("ruleTemplates", pagedVoiceTemplates.getPageList());

    return "plan/quickViewVoiceRuleTemplate";
  }

  @RequestMapping(value="/quickViewMsgTimeTemplate.html")
  public String quickViewMsgTimeTemplate(Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationTime> pagedVoiceTemplates = timeQueryService.findAllTimeTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedVoiceTemplates, request);
    
    modelMap.put("timeTemplates", pagedVoiceTemplates.getPageList());

    return "plan/quickViewMsgTimeTemplate";
  }

  @RequestMapping(value="/quickViewVoiceTimeTemplate.html")
  public String quickViewVoiceTimeTemplate(Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<CommunicationTime> pagedVoiceTemplates = timeQueryService.findAllTimeTemplatesByPage(index[0], index[1]);
    pagedHelper.processPage(pagedVoiceTemplates, request);
    
    modelMap.put("timeTemplates", pagedVoiceTemplates.getPageList());

    return "plan/quickViewVoiceTimeTemplate";
  }

  @RequestMapping(value="/quickViewPreviewOrder.html")
  public String quickViewPreviewOrder(Map modelMap, HttpServletRequest request) {
    PagedQueryControllerAdapter pagedHelper = new PagedQueryControllerAdapter();
    int[] index = pagedHelper.getIndex(request);
    PagedListHandler<PreviewOrder> pagedPreviewOrders =legacyQueryService.findAllPreviewOrdersByPage(index[0], index[1]);
    pagedHelper.processPage(pagedPreviewOrders, request);
    
    modelMap.put("previewOrders", pagedPreviewOrders.getPageList());

    return "plan/quickViewPreviewOrder";
  }
  //<-
  
  //预览功能区->
  @RequestMapping(value="/previewSMS.html")
  public void previewSMS(@ModelAttribute DefaultTemplateForm form, Map modelMap, HttpServletResponse response) {
    response.setContentType("text/html");
    response.setCharacterEncoding("gbk");

    PrintWriter out = null;
    try {
      out = new PrintWriter(response.getOutputStream());
      
      String txtAreaContent = queryFacade.getMessagePreviewBy(form.getMsgNodeSlt(), form.getMessageTemplateIdTxt(), 
          form.getMsgRuleTemplateIdTxt(), form.getMsgTimeTemplateIdTxt(), form.getMsgProductTypeSlt(), 
          form.getMsgConditionTypeSlt(), form.getMsgConditionSlt(), form.getMsgEnabledSlt());
      txtAreaContent = new String(txtAreaContent.getBytes("gbk"), "gbk");
      
      out.write(txtAreaContent);
      
//可取得内容的实现
//      String rtnSMSInfo = queryFacade.getMessageTemplateBy(form.getPreviewOrderIdTxt(), form.getMessageTemplateIdTxt(), form.getMsgTimeTemplateIdTxt());
//      
//      if ("x".equals(rtnSMSInfo)) {        
//        out.write("短信内容读取失败，无法预览");
//      } else {
//        out.write("短信描述：" + msgQueryService.findCommunicationMessageBy(form.getMessageTemplateIdTxt()).getSmsDescription());
//        out.println();
//        out.write("短信内容：" + rtnSMSInfo.substring(20));
//        out.println();
//        out.write("短信预定发送时间：" + rtnSMSInfo.substring(1, 20));
//      }

      out.close();
      
    } catch (IOException e) {
      e.printStackTrace();
      if (out != null) {
        out.write("");
        out.close();
      }
    }
  }
  
  @RequestMapping(value="/previewSMSTemplateMapping.html")
  public void previewSMSTemplateMapping(@RequestParam("smsMappingId") String smsMappingId, Map modelMap, HttpServletResponse response) {
    response.setContentType("text/html");
    response.setCharacterEncoding("gbk");

    PrintWriter out = null;
    try {
      out = new PrintWriter(response.getOutputStream());
      
      SMSTemplateMapping mapping = queryService.findSMSTemplateMappingBy(Long.valueOf(smsMappingId));
      
      CommunicationMessage msgTemplate = mapping.getMsgTemplate();
      CommunicationRule msgRuleTemplate = mapping.getMsgRuleTemplate();
      CommunicationTime msgTimeTemplate = mapping.getMsgTimeTemplate();
      
      String msgCustomId = "";
      String ruleCustomId = "";
      String timeCustomId = "";
      if (msgTemplate != null) msgCustomId = msgTemplate.getCustomId();
      if (msgRuleTemplate != null) ruleCustomId = msgRuleTemplate.getCustomId();
      if (msgTimeTemplate != null) timeCustomId = msgTimeTemplate.getCustomId();
      
      String txtAreaContent = queryFacade.getMessagePreviewBy(mapping.getMsgNode(), msgCustomId, 
          ruleCustomId, timeCustomId, mapping.getMsgProductType(), 
          mapping.getMsgConditionType(), mapping.getMsgCondition(), mapping.isMsgCommunicationEnabled()?"1":"0");
      txtAreaContent = new String(txtAreaContent.getBytes("gbk"), "gbk");
      
      out.write(txtAreaContent);
      
//可取得内容的实现
//      String rtnSMSInfo = queryFacade.getMessageTemplateBy(form.getPreviewOrderIdTxt(), form.getMessageTemplateIdTxt(), form.getMsgTimeTemplateIdTxt());
//      
//      if ("x".equals(rtnSMSInfo)) {        
//        out.write("短信内容读取失败，无法预览");
//      } else {
//        out.write("短信描述：" + msgQueryService.findCommunicationMessageBy(form.getMessageTemplateIdTxt()).getSmsDescription());
//        out.println();
//        out.write("短信内容：" + rtnSMSInfo.substring(20));
//        out.println();
//        out.write("短信预定发送时间：" + rtnSMSInfo.substring(1, 20));
//      }

      out.close();
      
    } catch (IOException e) {
      e.printStackTrace();
      if (out != null) {
        out.write("");
        out.close();
      }
    }
  }
  
  @RequestMapping(value="/previewVoice.html")
  public void previewVoice(@ModelAttribute DefaultTemplateForm form, Map modelMap, HttpServletResponse response) {
    response.setContentType("text/html");
    response.setCharacterEncoding("gbk");

    PrintWriter out = null;
    try {
      out = new PrintWriter(response.getOutputStream());
      String txtAreaContent = queryFacade.getVoicePreviewBy(form.getVoiceNodeSlt(), form.getVoiceTemplateIdTxt(), 
          form.getVoiceRuleTemplateIdTxt(), form.getVoiceTimeTemplateIdTxt(), form.getVoiceProductTypeSlt(), 
          form.getVoiceConditionTypeSlt(), form.getVoiceConditionSlt(), form.getVoiceEnabledSlt());
      txtAreaContent = new String(txtAreaContent.getBytes("gbk"), "gbk");
      
      out.write(txtAreaContent);

      
//取得内容的实现
//      String rtnVoiceInfo = queryFacade.getVoiceTemplateBy(form.getPreviewOrderIdTxt(), form.getVoiceTemplateIdTxt(), form.getVoiceTimeTemplateIdTxt());
//      
//      if ("x".equals(rtnVoiceInfo)) {        
//        out.write("语音内容读取失败，无法预览");
//      } else {
//        out.write("语音描述：" + voiceQueryService.findCommunicationVoiceBy(form.getVoiceTemplateIdTxt()).getVoiceDescription());
//        out.println();
//        out.write("语音内容：" + rtnVoiceInfo.substring(20));
//        out.println();
//        out.write("语音预定发送时间：" + rtnVoiceInfo.substring(1, 20));
//      }

      out.close();
      
    } catch (IOException e) {
      e.printStackTrace();
      if (out != null) {
        out.write("");
        out.close();
      }
    }
  }
  //<-
  
  @RequestMapping(value="/previewVoiceTemplateMapping.html")
  public void previewVoiceTemplateMapping(@RequestParam("voiceMappingId") String voiceMappingId, Map modelMap, HttpServletResponse response) {
    response.setContentType("text/html");
    response.setCharacterEncoding("gbk");

    PrintWriter out = null;
    try {
      out = new PrintWriter(response.getOutputStream());
      
      VoiceTemplateMapping mapping = queryService.findVoiceTemplateMappingBy(Long.valueOf(voiceMappingId));
      
      CommunicationVoice voiceTemplate = mapping.getVoiceTemplate();
      CommunicationRule voiceRuleTemplate = mapping.getVoiceRuleTemplate();
      CommunicationTime voiceTimeTemplate = mapping.getVoiceTimeTemplate();
      
      String voiceCustomId = "";
      String ruleCustomId = "";
      String timeCustomId = "";
      if (voiceTemplate != null) voiceCustomId = voiceTemplate.getCustomId();
      if (voiceRuleTemplate != null) ruleCustomId = voiceRuleTemplate.getCustomId();
      if (voiceTimeTemplate != null) timeCustomId = voiceTimeTemplate.getCustomId();
      
      String txtAreaContent = queryFacade.getVoicePreviewBy(mapping.getVoiceNode(), voiceCustomId, 
          ruleCustomId, timeCustomId, mapping.getVoiceProductType(), 
          mapping.getVoiceConditionType(), mapping.getVoiceCondition(), mapping.isVoiceCommunicationEnabled()?"1":"0");
      txtAreaContent = new String(txtAreaContent.getBytes("gbk"), "gbk");
      
      out.write(txtAreaContent);

      out.close();
      
    } catch (IOException e) {
      e.printStackTrace();
      if (out != null) {
        out.write("");
        out.close();
      }
    }
  }

  @RequestMapping(value="/newDefaultTemplate.html")
  public String newDefaultTemplate(@ModelAttribute DefaultTemplateForm form) {
    DefaultCommunicationTemplate defaultTemplate = new DefaultCommunicationTemplate();
    
    defaultTemplate.setDescription(form.getDescriptionTxt());
    
    if("sms".equals(form.getSmsorvoicekey())) {
      
      //添加短信关联->
      SMSTemplateMapping smsMapping = new SMSTemplateMapping();
      smsMapping.setMsgNode(form.getMsgNodeSlt());
      smsMapping.setMsgProductType(form.getMsgProductTypeSlt());
      smsMapping.setMsgConditionType(form.getMsgConditionTypeSlt());
      smsMapping.setMsgCondition(form.getMsgConditionSlt());
      smsMapping.setMsgCommunicationEnabled("1".equals(form.getMsgEnabledSlt())?true:false);
    
      smsMapping.setMsgTemplate(msgQueryService.findCommunicationMessageBy(form.getMessageTemplateIdTxt()));    
      smsMapping.setMsgTimeTemplate(timeQueryService.findCommunicationTimeBy(form.getMsgTimeTemplateIdTxt()));

      smsMapping.setMsgRuleTemplate(ruleQueryService.findCommunicationRuleBy(form.getMsgRuleTemplateIdTxt()));
      
      defaultTemplate.addSMSTemplateMapping(smsMapping);
      //<-
    } else {
      
      //添加语音关联->
      VoiceTemplateMapping voiceMapping = new VoiceTemplateMapping();
      voiceMapping.setVoiceNode(form.getVoiceNodeSlt());
      voiceMapping.setVoiceProductType(form.getVoiceProductTypeSlt());
      voiceMapping.setVoiceConditionType(form.getVoiceConditionTypeSlt());
      voiceMapping.setVoiceCondition(form.getVoiceConditionSlt());
      voiceMapping.setVoiceCommunicationEnabled("1".equals(form.getVoiceEnabledSlt())?true:false);
      
      voiceMapping.setVoiceTemplate(voiceQueryService.findCommunicationVoiceBy(form.getVoiceTemplateIdTxt()));    
      voiceMapping.setVoiceTimeTemplate(timeQueryService.findCommunicationTimeBy(form.getVoiceTimeTemplateIdTxt()));

      voiceMapping.setVoiceRuleTemplate(ruleQueryService.findCommunicationRuleBy(form.getVoiceRuleTemplateIdTxt()));
      
      defaultTemplate.addVoiceTemplateMapping(voiceMapping);
      //<-
    }
    
    //updateService.storeDefaultTemplate(rtnDefaultTemplate);
    
    DefaultCommunicationTemplate rtnDefaultTemplate = 
      updateService.storeDefaultTemplateAndtoLegacyDBAlso(defaultTemplate, form.getSmsorvoicekey());//同时也要向遗留系统数据库写入

    return "redirect:enterDefaultTemplateEditForm.html?updatekey="+rtnDefaultTemplate.getId();
  }

  @RequestMapping(value="/enterDefaultTemplateEditForm.html")
  public String enterEditDefaultTemplate(@RequestParam("updatekey") String defaultTemplateId, @ModelAttribute DefaultTemplateForm form, Map modelMap) {
    
    DefaultCommunicationTemplate template = queryService.findDefaultTemplateBy(Long.valueOf(defaultTemplateId));

    modelMap.put("defaultTemplate", template);
    
    //渲染节点下拉框
    List<Node> nodes = legacyQueryService.findAllNodes();
    Map<String, String> nodeMap = new LinkedHashMap();
    for (Node node : nodes) {
      nodeMap.put(node.getNcode(), node.getNname());
    }
    form.setNodeMap(nodeMap);
    
    //渲染产品类型下拉框
    List<ProductType> pTypes = legacyQueryService.findAllProductTypes();
    Map<String, String> productTypeMap = new LinkedHashMap();
    for (ProductType pType : pTypes) {
      productTypeMap.put(pType.getPcode(), pType.getPname());
    }
    form.setProductTypeMap(productTypeMap);
//    form.setMsgProductTypeSlt(template.getMsgProductType());
//    form.setVoiceProductTypeSlt(template.getVoiceProductType());
//    
//    //渲染条件类型下拉框
    List<ConditionType> cTypes = legacyQueryService.findAllConditionTypes();
    Map<String, String> conditionTypeMap = new LinkedHashMap();
    for (ConditionType cType : cTypes) {
      conditionTypeMap.put(cType.getCcode(), cType.getCname());
    }
    form.setConditionTypeMap(conditionTypeMap);
//    form.setMsgConditionTypeSlt(template.getMsgConditionType());
//    form.setVoiceConditionTypeSlt(template.getVoiceConditionType());
//    
//    //渲染条件值下拉框
    List<Condition> conditions = legacyQueryService.findAllConditions();
    Map<String, String> conditionMap = new LinkedHashMap();
    for (Condition c : conditions) {
      conditionMap.put(c.getCvcode(), c.getCvname());
    }
    form.setConditionMap(conditionMap);
//    form.setMsgConditionSlt(template.getMsgCondition());
//    form.setVoiceConditionSlt(template.getVoiceCondition());
    
    modelMap.put("smsMappings", template.getSmsTemplateMappings());
    modelMap.put("voiceMappings", template.getVoiceTemplateMappings());
    
    modelMap.put("nodeMap", nodeMap);
    modelMap.put("productTypeMap", productTypeMap);
    modelMap.put("conditionTypeMap", conditionTypeMap);
    modelMap.put("conditionMap", conditionMap);

    return "plan/editDefaultTemplateForm";
  }

  @RequestMapping(value="/editDefaultTemplate.html")
  public String editDefaultTemplate(@ModelAttribute DefaultTemplateForm form) {
    
    DefaultCommunicationTemplate defaultTemplate = queryService.findDefaultTemplateBy(Long.valueOf(form.getUpdatekey()));
    
    defaultTemplate.setDescription(form.getDescriptionTxt());
    
    if("sms".equals(form.getSmsorvoicekey())) {
      //添加短信关联->
      SMSTemplateMapping smsMapping = new SMSTemplateMapping();
      smsMapping.setMsgNode(form.getMsgNodeSlt());
      smsMapping.setMsgProductType(form.getMsgProductTypeSlt());
      smsMapping.setMsgConditionType(form.getMsgConditionTypeSlt());
      smsMapping.setMsgCondition(form.getMsgConditionSlt());
      smsMapping.setMsgCommunicationEnabled("1".equals(form.getMsgEnabledSlt())?true:false);
    
      smsMapping.setMsgTemplate(msgQueryService.findCommunicationMessageBy(form.getMessageTemplateIdTxt()));    
      smsMapping.setMsgTimeTemplate(timeQueryService.findCommunicationTimeBy(form.getMsgTimeTemplateIdTxt()));

      smsMapping.setMsgRuleTemplate(ruleQueryService.findCommunicationRuleBy(form.getMsgRuleTemplateIdTxt()));
      
      defaultTemplate.addSMSTemplateMapping(smsMapping);
      //<-
    } else {
      //添加语音关联->
      VoiceTemplateMapping voiceMapping = new VoiceTemplateMapping();
      voiceMapping.setVoiceNode(form.getVoiceNodeSlt());
      voiceMapping.setVoiceProductType(form.getVoiceProductTypeSlt());
      voiceMapping.setVoiceConditionType(form.getVoiceConditionTypeSlt());
      voiceMapping.setVoiceCondition(form.getVoiceConditionSlt());
      voiceMapping.setVoiceCommunicationEnabled("1".equals(form.getVoiceEnabledSlt())?true:false);
    
      voiceMapping.setVoiceTemplate(voiceQueryService.findCommunicationVoiceBy(form.getVoiceTemplateIdTxt()));
      voiceMapping.setVoiceTimeTemplate(timeQueryService.findCommunicationTimeBy(form.getVoiceTimeTemplateIdTxt()));

      voiceMapping.setVoiceRuleTemplate(ruleQueryService.findCommunicationRuleBy(form.getVoiceRuleTemplateIdTxt()));
      
      defaultTemplate.addVoiceTemplateMapping(voiceMapping);
    }
    
    //添加语音关联->
//    VoiceTemplateMapping voiceMapping = new VoiceTemplateMapping();
//    voiceMapping.setVoiceNode(form.getVoiceNodeSlt());
//    voiceMapping.setVoiceProductType(form.getVoiceProductTypeSlt());
//    voiceMapping.setVoiceConditionType(form.getVoiceConditionTypeSlt());
//    voiceMapping.setVoiceCondition(form.getVoiceConditionSlt());
//    voiceMapping.setVoiceCommunicationEnabled("1".equals(form.getVoiceEnabledSlt())?true:false);
//    
//    voiceMapping.setVoiceTemplate(voiceQueryService.findCommunicationVoiceBy(form.getVoiceTemplateIdTxt()));    
//    voiceMapping.setVoiceTimeTemplate(timeQueryService.findCommunicationTimeBy(form.getVoiceTimeTemplateIdTxt()));
//
//    voiceMapping.setVoiceRuleTemplate(ruleQueryService.findCommunicationRuleBy(form.getVoiceRuleTemplateIdTxt()));
//    
//    defaultTemplate.addVoiceTemplateMapping(voiceMapping);
    //<-
    
    //节点
//    defaultTemplate.setMsgNode(form.getMsgNodeSlt());
//    defaultTemplate.setVoiceNode(form.getVoiceNodeSlt());
//    //产品类型
//    defaultTemplate.setMsgProductType(form.getMsgProductTypeSlt());
//    defaultTemplate.setVoiceProductType(form.getVoiceProductTypeSlt());
//    //条件类型
//    defaultTemplate.setMsgConditionType(form.getMsgConditionTypeSlt());
//    defaultTemplate.setVoiceConditionType(form.getVoiceConditionTypeSlt());
//    //条件值    
//    defaultTemplate.setMsgCondition(form.getMsgConditionSlt());
//    defaultTemplate.setVoiceCondition(form.getVoiceConditionSlt());
//    
//    //通信启用
//    defaultTemplate.setMsgCommunicationEnabled("1".equals(form.getMsgEnabledSlt())?true:false);
//    defaultTemplate.setVoiceCommunicationEnabled("1".equals(form.getVoiceEnabledSlt())?true:false);
//    
//    //短信/语音 模板编号
//    defaultTemplate.setMsgTemplate(msgQueryService.findCommunicationMessageBy(form.getMessageTemplateIdTxt()));
//    defaultTemplate.setVoiceTemplate(voiceQueryService.findCommunicationVoiceBy(form.getVoiceTemplateIdTxt()));
//    
//    //短信/语音 通信规则编号
//    defaultTemplate.setMsgRuleTemplate(ruleQueryService.findCommunicationRuleBy(form.getMsgRuleTemplateIdTxt()));
//    defaultTemplate.setVoiceRuleTemplate(ruleQueryService.findCommunicationRuleBy(form.getVoiceRuleTemplateIdTxt()));
//    
//    //短信/语音 通信时间编号    
//    defaultTemplate.setMsgTimeTemplate(timeQueryService.findCommunicationTimeBy(form.getMsgTimeTemplateIdTxt()));    
//    defaultTemplate.setVoiceTimeTemplate(timeQueryService.findCommunicationTimeBy(form.getVoiceTimeTemplateIdTxt()));



    
    DefaultCommunicationTemplate rtnDefaultTemplate = 
      updateService.storeDefaultTemplateAndtoLegacyDBAlso(defaultTemplate, form.getSmsorvoicekey());//同时也要向遗留系统数据库写入

    //return "redirect:defaultTemplateMain.html";

    return "redirect:enterDefaultTemplateEditForm.html?updatekey="+rtnDefaultTemplate.getId();
  }

  @RequestMapping(value="/removeDefaultTemplate.html")
  public String removeDefaultTemplate(@RequestParam("keys") String keys,
                            Map modelMap, HttpServletRequest request) {
    String[] dTemplateIds = keys.split(",");

    for (int i = 0; i < dTemplateIds.length; i++) {
      updateService.removeDefaultTemplateAndLegacyDBAlsoBy(Long.valueOf(dTemplateIds[i]));
    }
    return "redirect:defaultTemplateMain.html";
  }

  @RequestMapping(value="/removeSMSMapping.html")
  public String removeSMSMapping(@RequestParam("deleteSmsKeys") String keys,@RequestParam("updatekey") String updateKey,
                            Map modelMap, HttpServletRequest request) {
    String[] subMsgTemplateIds = keys.split(",");

    for (int i = 0; i < subMsgTemplateIds.length; i++) {
      updateService.removeSubMsgTemplateOfDefaultTemplateBy(Long.valueOf(subMsgTemplateIds[i]));
    }

    return "redirect:enterDefaultTemplateEditForm.html?updatekey="+updateKey;
  }

  @RequestMapping(value="/removeVoiceMapping.html")
  public String removeVoiceMapping(@RequestParam("deleteVoiceKeys") String keys,@RequestParam("updatekey") String updateKey,
                            Map modelMap, HttpServletRequest request) {
    String[] subVoiceTemplateIds = keys.split(",");

    for (int i = 0; i < subVoiceTemplateIds.length; i++) {
      updateService.removeSubVoiceTemplateOfDefaultTemplateBy(Long.valueOf(subVoiceTemplateIds[i]));
    }

    return "redirect:enterDefaultTemplateEditForm.html?updatekey="+updateKey;
  }

  @RequestMapping(value="/enableDefaultTemplate.html")
  public String enableDefaultTemplate(@RequestParam("enableKey") String defaultTemplateId, Map modelMap) {
    
    updateService.enableDefaultTemplateBy(Long.valueOf(defaultTemplateId));
    
    return "redirect:defaultTemplateMain.html";
  }

}
